import { Input, Modal } from "antd";
import React, { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react";

export interface ITitleEditorModalProps {
  dialogTitle:string,
  value?:string,
  visible:boolean,
  
  onOk?:(value)=>void
  onCancel?: ()=>void
  onChange?:(value)=>void

}
const TitleEditorModal = forwardRef((props:ITitleEditorModalProps , ref)=>{

    const inputRef = useRef(null);
    const [value,setValue] = useState(props.value||'')
    useImperativeHandle(ref, () => inputRef.current);
    useEffect(()=>{
      /**
       * Modal诡异，visible了，还是找不到ref
       */
      setTimeout(()=>{
        ref =inputRef
        if( ref.current ){
          try{
            (ref.current as any).input.focus()
          }catch(e){
            
          }
          //ref.current.focus()
        }
      },100)
      
      
    },[props.visible])
    
    return (
      <Modal
        title={props.dialogTitle}
        visible={props.visible}
        cancelText="取消"
        okText="确定"
        onOk={()=>{
          props.onOk && props.onOk(value)
          setValue('')
        }}
        onCancel={()=>{
          props.onCancel && props.onCancel()
        }}
      >
      <div>
        <Input ref={inputRef} value={value} onChange={(e)=>{
          setValue(e.target.value)
          props.onChange && props.onChange(e.target.value)
        }} onPressEnter={()=>{
          if( value ){
            props.onOk && props.onOk(value)
            setValue('')
          }
          
        }} />
      </div>
    </Modal>
    )
})

export { TitleEditorModal }
